package com.chis.jmdatatimer.comm;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 
 * @Description 
 * @Company zwx
 * @author wlj
 * @version 2018年03月30日
 */
public class JedisConnect {
    /** 单例 */
    private static JedisConnect _singleton;
    /** 内存库配置文件 */
    public Properties prop;
    /** 通用库 */
    public ShardedJedisPool jedisPool;

    /**
     * 构造方法加载配置文件
     */
    private JedisConnect() {
        prop = new Properties();
        // 读取文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
        try {
            // 加载到对象
            prop.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取单例对象
     *
     * @return 单例对象
     */
    public static synchronized final JedisConnect getInstance() {
        if (_singleton == null) {
            _singleton = new JedisConnect();
            _singleton.initialize();
        }
        return _singleton;
    }

    /**
     * 初始化内存库连接池
     */
    public void initialize() {
        JedisPoolConfig cgs = new JedisPoolConfig();
        cgs.setMaxTotal(Integer.parseInt(prop.get("redis.pool.maxActive").toString()));
        cgs.setMaxIdle(Integer.parseInt(prop.get("redis.pool.maxIdle").toString()));
        cgs.setMaxWaitMillis(Long.parseLong(prop.get("redis.pool.maxWait").toString()));
        cgs.setTestOnBorrow(Boolean.parseBoolean(prop.get("redis.pool.testOnBorrow").toString()));
        cgs.setTestOnReturn(Boolean.parseBoolean(prop.get("redis.pool.testOnReturn").toString()));
        List<JedisShardInfo> shards = new ArrayList<>();
        JedisShardInfo si = new JedisShardInfo(prop.get("redis.ip").toString(), Integer.parseInt(prop.get("redis.port").toString()));
        si.setPassword(prop.get("redis.auth").toString());
        shards.add(si);
        jedisPool = new ShardedJedisPool(cgs, shards);

    }

}
